<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Db
 * Manage manipulations with MySQL, using singleton
 * @author zelic
 */
class Db {

    var $connection;

    /**
     * Fetch mode for select statement
     */

    const FETCH_ARRAY = 1;
    const FETCH_ASSOC = 2;
    const FETCH_CLASS = 3;

    public function __construct() {
        $this->open();
    }

    public function open() {
        if ($this->connection == null) {
            try {
                $host = Config::getConfig("db", "host");
                $username = Config::getConfig("db", "username");
                $password = Config::getConfig("db", "password");
                $database = Config::getConfig("db", "database");
                $encode = Config::getConfig("db", "encode");
                $this->connection = new PDO("mysql:host=$host;dbname=$database", $username, $password);
                $this->connection->exec("SET CHARACTER SET $encode");
                $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            } catch (PDOException $ex) {
                Logger::error($ex);
            }
        }
    }

    public function close() {
        if ($this->connection != null) {
            $this->connection = null;
        }
    }

    public function query($statement, $fetchMode = Db::FETCH_ARRAY) {
        if ($statement != null && strlen($statement) > 0) {
            $fmode = 0;
            switch ($fetchMode) {
                case Db::FETCH_ARRAY:
                    $fmode = PDO::FETCH_NUM;
                    break;
                case Db::FETCH_ASSOC:
                    $fmode = PDO::FETCH_ASSOC;
                    break;
                default:
                    $fmode = PDO::FETCH_ASSOC;
                    break;
            }
            $result = $this->connection->query($statement, $fmode);
            if ($result != null) {
                return $result;
            }
        }
        return false;
    }

    public function execute($statement) {
        try {
            if ($statement != null && strlen($statement) > 0) {
                return $this->connection->exec($statement);
            }
        } catch (PDOException $ex) {
            Logger::error($ex);
        }
        return false;
    }

    public function lastInsertId() {
        return $this->connection->lastInsertId();
    }

    public function getStatement() {
        Loader::loadClass("Statement");
        return new Statement();
    }

    public function __destruct() {
        $this->close();
    }

}

?>
